package com.huobao.yunying.activitys_store;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ViewInject;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.huobao.yunying.adapters.Adapter_Store_Progect_list;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.entity.Hot_saleslist;
import com.huobao.yunying.entity.StoreProgectList;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.ImageUtils;
import com.huobao.yunying.utils.ImageUtils.OnImageLoadListener;
import com.huobao.yunying.utils.SkipUtils;
import com.huobao.yunying.utils.Utils;
import com.huobao.zhangying.R;
import com.xrz.sxm.base.utils.ScreenUtil;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 店铺
 *
 * @author Administrator
 */
public class Act_Store extends HuobaoBaseActivity implements OnItemClickListener {

	///////////////////////////////////////headview
	@ViewInject(R.id.imgView)
	private ImageView imgView_top;
	@ViewInject(R.id.rtly_top)
	private RelativeLayout rtly_top;
	// 商家logo
	@ViewInject(R.id.imageview)
	private ImageView imageview;
	// 商家名字
	@ViewInject(R.id.tv_name)
	private TextView tv_name;
	// 收藏数量
	@ViewInject(R.id.tv_savenumber)
	private TextView tv_savenumber;
	// 筛选的View,点击更多时显示
	@ViewInject(R.id.llyt_shaixuan)
	private View view_shaixuan;
	// 价格输入的View
	@ViewInject(R.id.llyt_price_select)
	private View view_price_select;
	// 更多的View,点击之后隐藏
	@ViewInject(R.id.llyt_more)
	private View view_More;
	// 价格区间开始
	@ViewInject(R.id.edt_price_from)
	private EditText edt_price_from;
	// 价格区间结束
	@ViewInject(R.id.edt_price_to)
	private EditText edt_price_to;
	@ViewInject(R.id.btn_1)
	private Button btn_1;
	@ViewInject(R.id.btn_2)
	private Button btn_2;

	@ViewInject(R.id.tv_store_content)
	private TextView tv_store_content;
	//////////////////////////////////////////////////////////


	@ViewInject(R.id.scrollview)
	private PullToRefreshScrollView scrollview;

	@ViewInject(R.id.llyt_10)
	private View view_foreBtn;

	// 店铺id
	private String id;


	private Adapter_Store_Progect_list adapter;
	@ViewInject(R.id.gridview)
	private GridView gridview;


	@ViewInject(R.id.edt_search)
	private EditText edt_search;

	@ViewInject(R.id.tv_search)
	private TextView tv_search;

	/**
	 * 综合时需要用到
	 */
	private List<Hot_saleslist> listTemp;
	private List<Hot_saleslist> sales;

	@ViewInject(R.id.tv_save)
	private TextView tv_save;

	@ViewInject(R.id.view_hight)
	private View view_hight;

	@ViewInject(R.id.img_arrow)
	private ImageView img_arrow;
	private int lineCount;//店铺说明一共有几行

	@Override
	protected int getContentView() {
		return R.layout.layout_store;
	}

	@Override
	protected String getTitleText() {
		return null;
	}

	public void onCallClick(View vi) {
		if (tel == null)
			return;
		Uri uri = Uri.parse("tel:" + tel);
		Intent intent = new Intent(Intent.ACTION_DIAL, uri);
		startActivity(intent);
	}

	public void onYouhuiquanClick(View v) {
		Intent intent = new Intent(this, Act_Youhuiquan.class);
		intent.putExtra("id", id);
		startActivity(intent);
	}

	private int m_CurrentPage = 1;

	@Override
	protected void init() {
		addEmptyView();
		gridview.setOnItemClickListener(this);
		id = getIntent().getStringExtra("id");
		adapter = new Adapter_Store_Progect_list(context);
		gridview.setAdapter(adapter);
		getStoreData();
		getAllGoods();
		scrollview.setMode(Mode.BOTH);
		scrollview.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				m_CurrentPage = 1;
				getAllGoods();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				m_CurrentPage++;
				getAllGoods();
			}
		});
		tv_save.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				onSaveClick();
			}
		});
		tv_search.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				onSearchCLick();
			}
		});
		img_arrow.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if(lineCount == 0)return;
				String tag = (String) img_arrow.getTag();
				if(tag.equals("close")){//当前是关闭状态，需要变成开启状态
					tv_store_content.setLines(lineCount);
					img_arrow.setImageResource(R.mipmap.arrow_up);
					img_arrow.setTag("open");
				}else if(tag.equals("open")){
					tv_store_content.setLines(2);
					img_arrow.setImageResource(R.mipmap.arrow_down);
					img_arrow.setTag("close");
				}
			}
		});
	}


	private void getAllGoods() {
//		scrollview.setMode(Mode.BOTH);
//		rtly_top.setVisibility(View.GONE);
//		view_foreBtn.setVisibility(View.GONE);
//		view_More.setVisibility(View.GONE);
//		view_shaixuan.setVisibility(View.GONE);
		Map<String, String> map = HttpUtil.getParams("app", "store", "act", "product", "id", id, "page", m_CurrentPage + "");
		Http.getInstant().sendRequest(context, false, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				List<Hot_saleslist> list = JSON.parseArray(jsonObject.getString("retval"), Hot_saleslist.class);
				if (m_CurrentPage == 1)
					adapter.clear();
				adapter.addAll(list);
				scrollview.onRefreshComplete();
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

//	private void initHeadView(View headView){
//		imgView_top = (ImageView) headView.findViewById(R.id.imgView);
//		rtly_top = (RelativeLayout) headView.findViewById(R.id.rtly_top);
//			imageview = (ImageView) headView.findViewById(R.id.rtly_top);
//			tv_name = (TextView) headView.findViewById(R.id.tv_name);
//			tv_savenumber = (TextView) headView.findViewById(R.id.tv_savenumber);
//			view_shaixuan = headView.findViewById(R.id.llyt_shaixuan);
//			view_price_select = headView.findViewById(R.id.llyt_price_select);
//			view_More = headView.findViewById(R.id.llyt_more);
//			edt_price_from = (EditText) headView.findViewById(R.id.edt_price_from);
//			edt_price_to = (EditText) headView.findViewById(R.id.edt_price_to);
//			btn_1 = (Button) headView.findViewById(R.id.btn_1);
//			btn_2 = (Button) headView.findViewById(R.id.btn_2);
//	}

	private void addEmptyView() {
		TextView emptyView = new TextView(context);
		emptyView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		emptyView.setText("很抱歉! 没有找到相关商品");
		emptyView.setGravity(Gravity.CENTER_HORIZONTAL);
		emptyView.setPadding(10, 10, 10, 10);
		emptyView.setVisibility(View.GONE);
		((ViewGroup) gridview.getParent()).addView(emptyView);
		gridview.setEmptyView(emptyView);
	}

	/**
	 * 收藏点击
	 */
	private void onSaveClick() {
		Map<String, String> map = HttpUtil.getParams("app", "store", "act", "storecollect", "id", id);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				tv_save.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.icon_store_save_press , 0 , 0 ) ;
				JSONObject jsonObject = JSON.parseObject(result);
				Toast.makeText(context, jsonObject.getString("retval"), Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	/**
	 * 店铺详情点击
	 *
	 * @param view
	 */
	public void onStoreDetailClick(View view) {
		Intent intent = new Intent(this, Act_Store_Detail.class);
		intent.putExtra("id", id);
		startActivity(intent);
	}

	/**
	 * 商品分类点击
	 *
	 * @param view
	 */
	public void onFenleiClick(View view) {
		Intent intent = new Intent(this, Act_Store_Fenlei.class);
		intent.putExtra("id", id);
		startActivity(intent);
	}

	/**
	 * 本店推荐，更多点击
	 *
	 * @param view
	 */
	public void onMoreClick(View view) {
		view_More.setVisibility(View.GONE);
		view_shaixuan.setVisibility(View.VISIBLE);
	}

	/**
	 * 返回按钮点击
	 *
	 * @param view
	 */
	public void onBackCLick(View view) {
		finish();
	}

	/**
	 * 综合点击
	 *
	 * @param view
	 */
	public void onZongheClick(View view) {
		adapter.clear();
		adapter.addAll(listTemp);
	}

	/**
	 * 新品点击
	 *
	 * @param view
	 */
	public void onXinpinCLick(View view) {
		List<Hot_saleslist> list = new ArrayList<Hot_saleslist>();
		list.addAll(sales);
		Collections.sort(list, new Comparator<Hot_saleslist>() {
			@Override
			public int compare(Hot_saleslist lhs, Hot_saleslist rhs) {
				return (int) (rhs.add_time - (lhs.add_time));
			}
		});
		adapter.clear();
		adapter.addAll(list);
	}

	/**
	 * 搜索按钮点击
	 *
	 */
	private void onSearchCLick() {
		String key = edt_search.getText().toString().trim();
		Intent intent = new Intent(this, Act_Store_Progect_List.class);
		intent.putExtra("cate_id", "");
		intent.putExtra("id", id);
		intent.putExtra("keyword", key);
		startActivity(intent);
	}

	/**
	 * 销量点击
	 *
	 * @param view
	 */
	public void onXiaoliangClick(View view) {
		List<Hot_saleslist> list = new ArrayList<Hot_saleslist>();
		list.addAll(sales);
		Collections.sort(list, new Comparator<Hot_saleslist>() {
			@Override
			public int compare(Hot_saleslist lhs, Hot_saleslist rhs) {
				return lhs.sales.compareTo(rhs.sales);
			}
		});
		adapter.clear();
		adapter.addAll(list);
	}

	/**
	 * 价格筛选按钮提交
	 *
	 * @param view
	 */
	public void onPriceSubmitClick(View view) {
		String from = edt_price_from.getText().toString().trim();
		String to = edt_price_to.getText().toString().trim();
		if (from.equals("") || to.equals("")) {
			Toast.makeText(context, "价格不能为空！", Toast.LENGTH_SHORT).show();
			return;
		}
		float f_from = Float.parseFloat(from);
		float f_to = Float.parseFloat(to);
		float max = Math.max(f_from, f_to);
		float min = Math.min(f_to, f_from);
		List<Hot_saleslist> list = new ArrayList<Hot_saleslist>();
		for (Hot_saleslist saleslist : sales) {
			float price = Float.parseFloat(saleslist.price);
			if (price >= min && price <= max) {
				list.add(saleslist);
			}
		}
		Collections.sort(list, new Comparator<Hot_saleslist>() {
			@Override
			public int compare(Hot_saleslist lhs, Hot_saleslist rhs) {
				return lhs.price.compareTo(rhs.price);
			}
		});
		adapter.clear();
		adapter.addAll(list);
		view_price_select.setVisibility(View.GONE);
		Utils.togSoftkeybord(context, edt_price_from, true);

	}

	public void compar() {

	}

	/**
	 * 筛选框上价格按钮点击，（价格输入框出现）
	 *
	 * @param view
	 */
	public void onPriceBntClick(View view) {
		int visi = view_price_select.getVisibility();
		if (visi == View.VISIBLE)
			view_price_select.setVisibility(View.GONE);
		else
			view_price_select.setVisibility(View.VISIBLE);
	}

	private void getStoreData() {
		Map<String, String> map = HttpUtil.getParams(HttpConst.FRIST_KEY, "store", "id", id);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				StoreProgectList progectList = JSON.parseObject(jsonObject.getString("retval"), StoreProgectList.class);
				jsonObject = jsonObject.getJSONObject("retval");
//				sales = JSON.parseArray(jsonObject.getString("hot_saleslist"), Hot_saleslist.class);
//				listTemp = sales;
//				progectList.hot_saleslist = sales;
				showDetail(progectList);
//				adapter.addAll(sales);
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	private String tel;



	protected void showDetail(StoreProgectList progectList) {
		tel = progectList.tel;
		String image = TextUtils.isEmpty(progectList.pic_slides) ? progectList.store_banner : progectList.pic_slides;
		ImageUtils.loadimg(imgView_top, image, new OnImageLoadListener() {

			@Override
			public void onLoadSuccess(Drawable drawable) {
				int newWidth = ScreenUtil.getInstant().getDisWidth(context);
				int newHight = newWidth * drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth();
				LayoutParams layoutParams = (LayoutParams) rtly_top.getLayoutParams();
				layoutParams.width = newWidth;
				layoutParams.height = newHight + Math.max(view_hight.getHeight(), imageview.getHeight());
				rtly_top.setLayoutParams(layoutParams);

				RelativeLayout.LayoutParams img_params = (RelativeLayout.LayoutParams) imgView_top.getLayoutParams();
				img_params.width = newWidth;
				img_params.height = newHight;
				imgView_top.setLayoutParams(img_params);
			}
		});
		ImageUtils.loadimg(imageview, progectList.store_logo);
		tv_name.setText(progectList.store_name);
		mAbTitleBar.setTitleText(progectList.store_name);
		tv_savenumber.setText(progectList.collect_mod);
		tv_save.setCompoundDrawablesWithIntrinsicBounds(0,progectList.is_collect == 0 ? R.mipmap.icon_store_save : R.mipmap.icon_store_save_press , 0 , 0 ) ;
		if(TextUtils.isEmpty(progectList.store_top_desc)){
			tv_store_content.setVisibility(View.GONE);
		}else{
			tv_store_content.setVisibility(View.VISIBLE);
			tv_store_content.setText(progectList.store_top_desc);
		}

		btn_1.setText(progectList.goods_count + "\n最新上架");
		btn_2.setText(progectList.goods_count + "\n热门商品");
		m_ViewTree = tv_store_content.getViewTreeObserver();
		m_ViewTree.addOnPreDrawListener(listener);

	}
	private ViewTreeObserver m_ViewTree;
	private ViewTreeObserver.OnPreDrawListener listener = new ViewTreeObserver.OnPreDrawListener() {
		@Override
		public boolean onPreDraw() {
			lineCount = tv_store_content.getLineCount();
			m_ViewTree.removeOnPreDrawListener(listener);
			if(lineCount >= 2){
				tv_store_content.setLines(2);
				img_arrow.setVisibility(View.VISIBLE);
			}else{
				tv_store_content.setLines(lineCount);
				img_arrow.setVisibility(View.GONE);
			}
			return true;
		}
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		SkipUtils.seeDetail(context, adapter.getItem(position).goods_id, adapter.getItem(position).default_image);
	}

}
